package com.zwxu.upload;

import com.alibaba.fastjson.JSON;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.regions.*;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

public class  AmazonS3ClientInstance{
    private AWSCredentials awsCredentials;

    private String ACCESS_KEY;

    private String SECRET_KEY;

    private String ENDPOINT;

    private AmazonS3 client;

    private TransferManager tm;

    public AmazonS3 getClient() {
        return client;
    }

    public void setClient(AmazonS3 client) {
        this.client = client;
    }

    public AmazonS3ClientInstance(String endpoint, String accessKey, String secretKey) {
        ACCESS_KEY = accessKey;
        SECRET_KEY = secretKey;
        ENDPOINT = endpoint;
        initClient();
    }

    /**
     * 创建连接，连接S3服务器
     */
    private void initClient() {
        if (awsCredentials == null) {
            awsCredentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
            ClientConfiguration clientConfig = new ClientConfiguration();
            clientConfig.setProtocol(Protocol.HTTP);
            clientConfig.setSignerOverride("S3SignerType");
            AmazonS3ClientBuilder clientBuilder = AmazonS3ClientBuilder.standard();
            clientBuilder.setClientConfiguration(clientConfig);
            AWSCredentialsProvider awsCredentialsProvider = new AWSCredentialsProvider() {
                @Override
                public AWSCredentials getCredentials() {
                    return awsCredentials;
                }

                @Override
                public void refresh() {

                }
            };
            clientBuilder.setCredentials(awsCredentialsProvider);
            EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ENDPOINT, Regions.US_EAST_1.getName());
            clientBuilder.setEndpointConfiguration(endpointConfiguration);
            client = clientBuilder.build();
            TransferManagerBuilder transferManagerBuilder = TransferManagerBuilder.standard();
            transferManagerBuilder.setS3Client(client);
            tm = transferManagerBuilder.build();
        }
    }

    public ObjectListing getBacketObjects(String bucketName, String prefix, Boolean isDelimiter) {
        if (StringUtils.isNullOrEmpty(bucketName)) {
            return null;
        }
        ListObjectsRequest objectsRequest = new ListObjectsRequest().withBucketName(bucketName);
        if (prefix != null && !prefix.isEmpty()) {
            objectsRequest = objectsRequest.withPrefix(prefix);
        }
        if (isDelimiter) {
            objectsRequest = objectsRequest.withDelimiter("/");
        }
        ObjectListing objects = client.listObjects(objectsRequest);
        return objects;
    }

    public boolean createDir(String bucketName, String folderPath) {
        if (StringUtils.isNullOrEmpty(bucketName) || StringUtils.isNullOrEmpty(folderPath)) {
            return false;
        }
        if (!folderPath.endsWith("/")) {
            folderPath = folderPath + "/";
        }
        ByteArrayInputStream local = new ByteArrayInputStream("".getBytes());
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(0);
        client.putObject(bucketName, folderPath, local, meta);
        return true;

    }

    public boolean upload(String bucketName, String objectKey, File uploadFile) {
        if (StringUtils.isNullOrEmpty(objectKey)) {
            return false;
        }
        if (StringUtils.isNullOrEmpty(bucketName) || uploadFile == null) {
            return false;
        }
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(uploadFile);
            client.putObject(bucketName, objectKey, inputStream, new ObjectMetadata());
            return true;
        } catch (Exception e) {
            System.out.println("上传文件异常");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    System.out.println("关闭文件流异常");
                }
            }
        }

        return false;
    }

    public String getDownloadUrl(String bucketName, String objectKey) {
        if (StringUtils.isNullOrEmpty(bucketName) || StringUtils.isNullOrEmpty(objectKey)) {
            return null;
        }
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName,
                objectKey);
        System.out.println(client.generatePresignedUrl(request));
        return client.generatePresignedUrl(request).toString();
    }


    public static void main(String[] args){
        /*
        AmazonS3ClientInstance amazonS3ClientInstance = new AmazonS3ClientInstance("10.167.168.29:7480",
                "ewogICAgIlJHV19UT0tFTiI6ewogICAgICAgICJpZCI6ImNlcGhBZG1pbiIsCiAgICAgICAgInR5cGUiOiJsZGFwIiwKICAgICAgICAidmVyc2lvbiI6MSwKICAgICAgICAia2V5IjoiYTkwNjQ0OWQ1NzY5ZmE3MzYxZDdlY2M2YWEzZjZkMjgiCiAgICB9Cn0=",
                "cephAdmin");

        amazonS3ClientInstance.upload("data","test/hello.txt",new File("D:\\data\\hello.txt"));
        */

        AmazonS3ClientInstance amazonS3ClientInstance = new AmazonS3ClientInstance("172.31.205.29:7480",
                "ewogICAgIlJHV19UT0tFTiI6ewogICAgICAgICJpZCI6ImNlcGhBZG1pbiIsCiAgICAgICAgInR5cGUiOiJsZGFwIiwKICAgICAgICAidmVyc2lvbiI6MSwKICAgICAgICAia2V5IjoiYTkwNjQ0OWQ1NzY5ZmE3MzYxZDdlY2M2YWEzZjZkMjgiCiAgICB9Cn0=",
                "cephAdmin");
        S3Object flag = amazonS3ClientInstance.getClient().getObject("data","spdong/数据集/456/");
        System.out.println(flag);



    }
}
